/**
 * Created by Administrator on 2017/11/6.
 */
//页面初始化
Param.initPageParam();
var storage = window.localStorage;
var HardwareInfo =storage.getItem('HardwareInfo')
var macAddress;
if(!HardwareInfo){
    layer.msg('硬件信息获取失败')
}else{
    macAddress = JSON.parse(HardwareInfo).macAddress
}
var user =storage.getItem('user')
var hospitalId =JSON.parse(user).unitId
log4j.info(macAddress,hospitalId)
/***********快速检索非处方对象属性定义 starting***********/
var expand_setting = {
    attribute: {"data-item-id": "id"},//放着要存在tr标签中的数据 key表示的是a标签中的属性  value表示的是json数据中的key
    param: {pageSize: 10},//url请求参数
    url: concatToken(Param.host_url + "/chg/charges_info/select_drug_srm_page"),
    method: "post",
    width: "700",//设置表格的宽度，不设置就不加
    paging: {
        pageNum: "pageNum",//表示这是第几页，后面的value表示的是服务器需要的key
        pageSize: "pageSize",//表示每页显示，后面的value表示的是服务器需要的key
        pageTotal: "pageTotal"//表示总页数，后面的value表示的是服务器需要的key
    },
    name: "search_chinaSpell",
    column: [
        {
            colspan: 6,
            text: "drgAndExaName",
            title: "药品/检查名称"
        },
        {
            colspan: 7,
            text: "drgRegionName",
            title: "药品产地名称"
        }
    ],
    rowClick: function ($tr, rowData, $input) {	//选中药品数据事件
        //当前焦点所在行
        var $inputtr = $input.parents("tr:first");
        //类型
        log4j.info(rowData);
        $inputtr.find("input[name=type]").val(rowData.type);
        $inputtr.find("input[name=state]").val(rowData.state);
        $inputtr.find("input[name=hospitalId]").val(rowData.hospitalId);
        $inputtr.find("input[name=rcpStoreId]").val(rowData.rcpStoreId);
        $inputtr.find("input[name=modId]").val(rowData.modId);
        $inputtr.find("input[name=catName]").val(rowData.catName);
        $inputtr.find("input[name=catCode]").val(rowData.catCode);
        //药品名称
        $inputtr.find("input[name=drgAndExaName]").val(rowData.drgAndExaName);
        /**规格*/
        $inputtr.find("input[name=speId]").val(rowData.speId);
        //$inputtr.find("td[colName=drgSpecification]").html(rowData.drgSpecification);
        //给药方式
        $inputtr.find("select[name=modName]").val(rowData.modId);
        //频次
        $inputtr.find("select[name=freEnName]").val(rowData.freEnName);
        //产地
        $inputtr.find("input[name=manIds]").val(rowData.manId);
        //价格
        $inputtr.find("input[name=price]").val(rowData.price);
        /***单次剂量单位获取 starting**/
        var units = [];
        if (rowData.minUnit != "" && rowData.minUnit != null) {
            units.push({unit: rowData.minUnit, value: ""});
        }
        if (rowData.doseUnit != "" && rowData.doseUnit != null) {
            units.push({unit: rowData.doseUnit, value: rowData.drgDose});
        }
        if (rowData.volumeUnit != "" && rowData.volumeUnit != null) {
            units.push({unit: rowData.volumeUnit, value: rowData.volume});
        }

        var unitHtml = '<select name="treDoseUnit">';
        $(units).each(function (index, item) {
            unitHtml += '<option value=' + item.unit + ' dose="' + item.value + '">' + item.unit + '</option>';
        });
        unitHtml += '</select>';
        //单次剂量单位html插入
        $inputtr.find("select[name=treDoseUnit]").parent().html(unitHtml);

        //包装单位
        $inputtr.find("input[name=drgPackingUnit]").val(rowData.drgPackingUnit);
        //单次剂量值
        var treOnceDose = $inputtr.find("select[name=treDoseUnit]").find("option:selected").attr("dose");
        $inputtr.find("input[name=treOnceDose]").val(treOnceDose);
        //给剂量单位绑定onchange事件，修改单位剂量
        $inputtr.find("select[name=treDoseUnit]").on("change", function () {
            treOnceDose = $inputtr.find("select[name=treDoseUnit]").find("option:selected").attr("dose");
            $inputtr.find("input[name=treOnceDose]").val(treOnceDose);
        });
        /***单次剂量单位获取 ending**/

        //给给药方式绑定onchange事件，修改分组序号
        modIdChangeEvent($inputtr);
        /**处方序号重新计算**/
        initTreNum();
        /**明细删除事件绑定*/
        bindDetailIconDelEvent();
        //回车事件绑定
        keydownEvent(initRowTemplate());

    }//单击行的事件,$tr表示单击的那行的
};
/***********快速检索对象属性定义 ending***********/
//获取用户Id
var userId = window.localStorage.chargeId;
function getUserId() {
    var userId = window.localStorage.chargeId;
    log4j.info(userId)
    if (userId) {
        return userId.split('=')[1];
    } else {
        return '';
    }
}
function init() {
    //给药方式
    // var usage_mode_data;
    ajaxNormalPost("/drug/usage_mode/select_list", {}, function (data) {
        // usage_mode_data = data.data;
        sessionStorage.setItem('usage_mode_data',JSON.stringify(data.data));
    }, false);

    //频次
    // var frequency_data;
    ajaxNormalPost("/drug/frequency/select_list", {}, function (data) {
        // frequency_data = data.data;
        sessionStorage.setItem('frequency_data',JSON.stringify(data.data));
    }, false);
    baseInfo();//基本信息
    createTable();//创建主表格
    //createOTC();//创建非处方

}
init();
//获取非处方单的钱
function getnotNomalMoney() {
    var arrayRecipeDetail = [];
    $("#table-data-right").find("tbody").find("tr").each(function () {
        var recipeAndExamineInfo = new Object();
        recipeAndExamineInfo.speId = $(this).find("input[name=speId]").val();
        log4j.info(recipeAndExamineInfo.speId);
        recipeAndExamineInfo.state = $(this).find("input[name=state]").val();//类别
        recipeAndExamineInfo.manId = $(this).find("input[name=manIds]").val();
        log4j.info(recipeAndExamineInfo.manId);
        recipeAndExamineInfo.hospitalId = $(this).find("input[name=hospitalId]").val();//医院名称
        recipeAndExamineInfo.rcpStoreId = $(this).find("input[name=rcpStoreId]").val();//药房序号
        recipeAndExamineInfo.modId = $(this).find("input[name=modId]").val();//药房序号
        log4j.info(recipeAndExamineInfo.rcpStoreId);
        recipeAndExamineInfo.rcpPosts = $(this).find("input[name=rcpPosts]").val();//贴数
        recipeAndExamineInfo.redUseDay = $(this).find("input[name=redUseDay]").val();//用药天数
        recipeAndExamineInfo.freEnName = $(this).find("input[name=freEnName]").val();//频次
        recipeAndExamineInfo.modName = $(this).find("input[name=modName]").val();//给药方式
        recipeAndExamineInfo.catCode = $(this).find("input[name=catCode]").val();//药品类别
        recipeAndExamineInfo.price = $(this).find("input[name=price]").val();//单价
        recipeAndExamineInfo.drgAndExaName = $(this).find("input[name=drgAndExaName]").val();//名称
        recipeAndExamineInfo.quantity = $(this).find("input[name=quantity]").val();//数量
        recipeAndExamineInfo.drgPackingUnit = $(this).find("input[name=drgPackingUnit]").val();//单位
        if (recipeAndExamineInfo.drgAndExaName !== null && recipeAndExamineInfo.drgAndExaName !== undefined && recipeAndExamineInfo.drgAndExaName !== '') {
            arrayRecipeDetail.push(recipeAndExamineInfo);
        }
    });
    log4j.info(arrayRecipeDetail);//非处方信息
    return arrayRecipeDetail;

}
//患者基本信息
function baseInfo() {
    ajaxNormalPost('/chg/charges_info/getChgInfoWrapper', {chargeId: userId}, function (res) {
        if (res) {
            console.log("好嗨哦=", res)
            $('#patName').text(res.data.patName || '');
            $('#patCardNum').text(res.data.patCardNum || '');
            $('#patSex').text(res.data.patSex == 1 ? '男' : '女');
            $('#patAge').text(res.data.patAge == undefined ? '' : res.data.patAge);
            $('#patContacts').text(res.data.patContacts || '');
            $('#feeName').text(res.data.feeName || '');
            $('#sffName').text(res.data.sffName || '');
            $('#depName').text(res.data.depName || '');
            $('#disTypeName').text(res.data.disTypeName || '普通');
            $('#patAddress').text(res.data.patAddress || '');
            $('#disName').text(res.data.disName || '');
            $('#usrNum').text('当前发票号码:' + (res.data.usrNum || ''));
            var cash = parseFloat((res.data.billCash.substr(0,res.data.billCash.length-1))  - (res.data.billOdd.substr(0,res.data.billOdd.length-1)))
            if(cash){
                $('#billCash').text((cash).toFixed(2) + '元');
            }else{
                $('#billCash').text('');
            }
            // if(res.data.feeId != 1 || res.data.feeId != '1'){
                //收费金额-billCash
                // $('#billCash').text(res.data.billCash || '');
                //账户----总金额billTotalFee
                var billTotalFee = res.data.charges.billTotalFee + '元'
                $('#billTotalFee').text(res.data.charges.billTotalFee + '元' || '');
                //本年账户余额
                // var currentYearBalance = res.data.charges.currentYearBalance + '元'
                // $('#currentYearBalance').text(currentYearBalance || '')
                // //本年账户支付
                // var currentYearPay = res.data.charges.currentYearPay + '元'
                // $('#currentYearPay').text(currentYearPay || '')
                // //历年账户余额
                // var calendarYearBalance = res.data.charges.calendarYearBalance + '元'
                // $('#calendarYearBalance').text(calendarYearBalance || '')
                // //历年账户支付
                // var calendarYearPay = res.data.charges.calendarYearPay + '元'
                // $('#calendarYearPay').text(calendarYearPay || '')
            // }else {
                // $('#currentYearBalance').text('0元')
                // $('#currentYearPay').text('0元')
                // $('#calendarYearBalance').text('0元')
                // $('#calendarYearPay').text('0元')
                // $('#billTotalFee').text('0元')
            // }
         $('#billOdd').text(res.data.billOdd || '');
            var billFavorFee = res.data.charges.billFavorFee + '元'
            $('#billFavorFee').text(billFavorFee || '');
        }
    })
}

//创建表格
function createTable() {
    ajaxNormalPost('/chg/charges_info/getReturnRecipeIdAndExaMineId', {chargeId: userId}, function (res) {
        if (res) {
            ajaxNormalPost('/chg/charges_info/getReturnRecipesAndExaMines', {
                recipeIds: res.data.recipeIds.join(','),
                examineIds: res.data.examineIds.join(',')
            }, function (res) {
                if (res.ret === 0) {
                    if (res.data.DJZY.length) {//中药
                        for (var i = 0; i < res.data.DJZY.length; i++) {
                            if(!res.data.DJZY[i].length){
                                continue;
                            }
                            createCN(res.data.DJZY[i],'代煎')
                        }
                    }
                    if (res.data.FDJZY.length) {//中药
                        for (var i = 0; i < res.data.FDJZY.length; i++) {
                            if(!res.data.FDJZY[i].length){
                                continue;
                            }
                            createCN(res.data.FDJZY[i],'非代煎')
                        }
                    }
                    if (res.data.XY.length) {//西药
                        for (var i = 0; i < res.data.XY.length; i++) {
                            if(!res.data.XY[i].length){
                                continue;
                            }
                            createWt(res.data.XY[i]);
                        }
                    }
                    if (res.data.JC.length) {
                        for (var i = 0; i < res.data.JC.length; i++) {//检查
                            if(!res.data.JC[i].length){
                                continue;
                            }
                            createJJ(res.data.JC[i], '检查开单');
                        }
                    }
                    if (res.data.JY.length) {
                        for (var i = 0; i < res.data.JY.length; i++) {//检验
                            if(!res.data.JY[i].length){
                                continue;
                            }
                            createJJ(res.data.JY[i], '检验开单');
                        }
                    }
                    if (res.data.XM.length) {
                        for (var i = 0; i < res.data.XM.length; i++) {//收费项
                            if(!res.data.XM[i].length){
                                continue;
                            }
                            createFee(res.data.XM[i]);
                        }
                    }
                } else {
                    layer.msg(res.msg)
                }
            })
        }
    })
}
//创建非处方药品
function createOTC() {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center">' +
        '<span>非处方药</span>'+
        '<i class="iconfont icon-xinzeng pull-right mr20" style="font-size:25px;color:#ccc" onclick="addRow()"></i>' +
        '</h4>' +
        '<table class="table table-fixed table-hover text-center" id="table-data-right">' +
        '<thead><tr>' +
        '<td colspan="1">序号</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="4">频次</td>' +
        '<td colspan="4">给药方式</td>' +
        '<td colspan="3">天数</td>' +
        '<td colspan="3">贴数</td>' +
        '<td colspan="3">数量</td>' +
        '<td colspan="3">单位</td>' +
        ' <td colspan="3">单价(元)</td>' +
        '<td colspan="2">操作</td>' +
        '</tr></thead>' +
        '<tbody>'+
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//增加非处方行
function addRow(frequency_data,usage_mode_data) {
    var row = initRowTemplate();
    //设置处方类别
    // $.extend(expand_setting.param, {"search_recipeType": $("#treType").val()});
    $("#table-data-right").find("tbody").append(row);
    $("#table-data-right").find("tbody").find("tr:last").find("input[name=drgAndExaName]").grayExpandTable(expand_setting);
    $("#table-data-right").find("tbody").find("tr:last").find("input[name=quantity]").on("input propertychange", function () {
        var prices = 0;
        $("#table-data-right").find("tbody").find("tr").each(function () {
            var quantity = Number($(this).find("input[name=quantity]").val().trim());
            var price = Number($(this).find("input[name=price]").val().trim());
            if (quantity === quantity && price === price) {
                prices += (quantity * price);
            }
        });
        $("#totalPrice_west").html(Math.floor(prices * 100) / 100);
    })
    /**处方序号重新计算**/
    initTreNum();
    // /**明细删除事件绑定*/
    bindDetailIconDelEvent();
    //
    keydownEvent(row);
}
/**非处方明细模板行定义**/
var self_row_index = 0;
function initRowTemplate() {
    //非处方明细行模板定义 starting
    var row = '<tr data-id="1"><input type="hidden" name="treId"><input type="hidden" name="state"><input type="hidden" name="modId">'
        + '<input type="hidden" name="treNum"><input type="hidden" name="speId"><input type="hidden" name="hospitalId">'
        + '<input type="hidden" name="manIds"><input type="hidden" name="treGroupNum"><input type="hidden" name="rcpStoreId">'
        + '<input type="hidden" name="catCode">'
        + '<td colspan="1" colName="treNum"></td>'
        + '<td colspan="2" colName="catName"><input type="text" name="catName" disabled="true"></td>'
        + '<td colspan="5" colName="drgAndExaName"><input type="text" name="drgAndExaName"></td>'
        //+ '<td colspan="3" colName="onceDose"><input type="text" name="onceDose"></td>'
        + '<td colspan="4" colName="freEnName"><select name="freEnName">';
    var frequency_data=JSON.parse(sessionStorage.getItem('frequency_data'));
    $(frequency_data).each(function (index, item) {
        row += '<option value=' + item.freEnName + '>' + item.freName + '</option>';
    });
    row += '</select></td>';
    row += '<td colspan="4" colName="modName"><select name="modName">';

    var usage_mode_data=JSON.parse(sessionStorage.getItem('usage_mode_data'));
    $(usage_mode_data).each(function (index, item) {
        row += '<option value=' + item.id + '>' + item.modName + '</option>';
    });
    row += '</select></td>';

    row += '<td colspan="3" colName="redUseDay"><input type="text" name="redUseDay"></td>'
        + '<td colspan="3" colName="rcpPosts"><input type="text" name="rcpPosts"></td>'//贴数
        + '<td colspan="3" colName="quantity"><input type="text" name="quantity"></td>'//数量
        //+ '<td colspan="3" colName="treDoseUnit"><select name="treDoseUnit"></select></td>'
        + '<td colspan="3" colName="drgPackingUnit"><input type="text" name="drgPackingUnit"></td>'
        + '<td colspan="3" colName="price"><input type="text" name="price"></td>';//单价
    row += '<td colspan="2"><i class="iconfont icon-shanchu detail-icon-del"></i></td></tr>';
    //协定处方明细行模板定义 ending
    return row;
}
/**给药方式绑定onchange事件，修改分组序号**/
function modIdChangeEvent($tr) {
    $tr.find("select[name=modId]").on("change", function () {
        var modId = $tr.find("select[name=modId]").val();
        //副药
        if (modId == 99) {
            if ($tr.find("td[colName=treNum]").text() == 1) {
                alert("请先添加主药!");
                return;
            }
            var pre_treGroupNum = $tr.prev().find("td[colName=treGroupNum]").text();
            $tr.find("td[colName=treGroupNum]").html(pre_treGroupNum);
            $tr.find("input[name=treGroupNum]").val(pre_treGroupNum);
        } else {
            $tr.find("td[colName=treGroupNum]").html($tr.find("td[colName=treNum]").text());
            $tr.find("input[name=treGroupNum]").val($tr.find("td[colName=treNum]").text());
        }
    });
}
/**分组序号重新计算**/
function initTreGroupNum() {
    $trs = $("#table-data-right").find("tbody").find("tr");
    $.each($trs, function (index, tr) {
        var modId = $(tr).find("select[name=modId]").val();
        //副药
        if (modId == 99) {
            $(tr).find("td[colName=treGroupNum]").html(index);
            $(tr).find("input[name=treGroupNum]").val(index);
            $("#totalCount_drugs").html(index);
        } else {
            $(tr).find("td[colName=treGroupNum]").html(index + 1);
            $(tr).find("input[name=treGroupNum]").val(index + 1);
            $("#totalCount_drugs").html(index + 1);
        }
    });
}
/**处方序号重新计算**/
function initTreNum() {
    $trs = $("#table-data-right").find("tbody").find("tr");
    $.each($trs, function (index, tr) {
        //添加处方序号
        $(tr).find("td[colName=treNum]").html(index + 1);
        $(tr).find("input[name=treNum]").val(index + 1);
        $("#totalCount_drugs").html(index + 1);
        //添加data-id属性
        $(tr).attr("data-id", index + 1);
    });
    //最后一行分组序号设置
    var $treGroupNum = $("#table-data-right").find("tbody").find("tr:last").find("td[colName=treGroupNum]");
    $treGroupNum.html($trs.length);
    //log4j.info($treGroupNum.html()+"总计");
}
/**获取硬件信息*/
function getSystemInfo(strINFOType, LODOP) {
    var LODOP = LODOP || getLodop();
    for (var i = 0; i < strINFOType.length; i++) {
        LODOP.GET_SYSTEM_INFO(strINFOType[i])
        if (LODOP.CVERSION) CLODOP.On_Return = function (TaskID, Value) {
            arr.push(Value);
            if(arr.length==3){
                sessionStorage.setItem('printTexts',JSON.stringify(arr))
            }
            throw new Error();
        };
    }
}
var LODOP; //声明为全局变量
function getSystemInfo(strINFOType){
    LODOP=getLodop();
    var strResult=LODOP.GET_SYSTEM_INFO(strINFOType);
    if (!LODOP.CVERSION) return strResult; else return "";

}


/**明细删除事件绑定*/
function bindDetailIconDelEvent() {
    $(".detail-icon-del").off("click");

    $(".detail-icon-del").on("click", function () {
        var $tr = $(this).parents("tr");
        /*var $prev_tr = $(this).parents("tr").prev();

         var treGroupNum = $tr.find("td[colName=treGroupNum]").text();
         var prev_treGroupNum = $prev_tr.find("td[colName=treGroupNum]").text();

         if (treGroupNum != prev_treGroupNum) {
         //删除所有分组需要相同的副药
         $next_tr_all = $(this).parents("tr").nextAll();
         $.each($next_tr_all, function(index, item){
         if ($(item).find("td[colName=treGroupNum]").text() == treGroupNum) {
         $(item).remove();
         }
         });

         //删除当前行
         $tr.remove();
         } */

        $tr.remove();
        /**处方序号重新计算**/
        initTreNum();
        /**分组序号重新计算**/
        initTreGroupNum();
    });
}
//定义回车事件处理方法
function keydownEvent(row) {
    var $nbp = $("#table-data-right input:text, #table-data-right select");
    $nbp.on("keydown", function (e) {
        var key = e.which;
        if (key == 13) {
            //如果焦点在最后一个元素，回车后添加新一行
            if ($(this).attr("name") == "price"
                && $(this).parents("tr").attr("data-id") == $("#table-data-right").find("tr:last").attr("data-id")) {

                //设置处方类别
                $.extend(expand_setting.param, {"search_recipeType": $("#treType").val()});
                $("#table-data-right").find("tbody").append(row);
                $("#table-data-right").find("tr:last").find("input[name=drgAndExaName]").grayExpandTable(expand_setting);

                $nbp.off("keydown");

                $nbp = $("#table-data-right input:text, #table-data-right select");
                var next = $nbp.index(this) + 1;
                $nbp.eq(next).focus();

                /**处方序号重新计算**/
                initTreNum();
                //重新绑定回车事件处理方法
                keydownEvent(row);
            } else {
                var next = $nbp.index(this) + 1;
                $nbp.eq(next).focus();
            }
        }
    });
}
//中药表格
function createCN(data, title) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        `<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()"
         onchange="toggleFee(this)">中药处方<span style="color: ${title.length == 3 ? '#000' : 'red'};font-weight: 700;">(${title})</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate  ml5"></i></h4>` +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-rd=' + data[0].recipeId + '>' +
        '<thead><tr>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="3">频次</td>' +
        '<td colspan="3">给药方式</td>' +
        '<td colspan="2">天数</td>' +
        '<td colspan="2">单次剂量</td>' +
        '<td colspan="2">贴数</td>' +
        '<td colspan="2">总剂量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '<td colspan="5">' + data[j].drgName + '</td>' +
            '<td colspan="3">' + data[j].freName + '</td>' +
            '<td colspan="3">' + data[j].modName + '</td>' +
            '<td colspan="2">' + data[j].redUseDay + '</td>' +
            '<td colspan="2">' + data[j].redOnceDose + '</td>' +
            '<td colspan="2">' + data[j].rcpPosts + '</td>' +
            '<td colspan="2">' + data[j].redQuantity + '</td>' +
            '<td colspan="2">' + data[j].drgPackingUnit + '</td>' +
            '<td colspan="2">' + data[j].redPrice + '</td>' +
            '<td colspan="2">' + data[j].redSumFee + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">'+ (data[j].chargeLevel == 1 ? '甲' : (data[j].chargeLevel == 2 ?'乙':'丙'))+'</td>' +
            '</tr>';
        sumFee += data[j].redSumFee;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"></td>' +
        '<td colspan="19" style="border-right:none" class="text-left">' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right switch-off">合计现金：' + (sumFee).toFixed(2) + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">合计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);


}
//西药表格
function createWt(data) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>西药开方</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-rd=' + data[0].recipeId + '>' +
        '<thead><tr>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">给药方式</td>' +
        '<td colspan="2">频次</td>' +
        '<td colspan="2">用药天数</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '<td colspan="5">' + data[j].drgName + '</td>' +
            '<td colspan="2">' + data[j].redDoseUnit + '</td>' +
            '<td colspan="2">' + data[j].modName + '</td>' +
            '<td colspan="2">' + data[j].freName + '</td>' +
            '<td colspan="2">' + data[j].redUseDay + '</td>' +
            '<td colspan="2">' + data[j].redQuantity + '</td>' +
            '<td colspan="2">' + data[j].redPrice + '</td>' +
            '<td colspan="2">' + data[j].redSumFee + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">'+ (data[j].chargeLevel == 1 ? '甲' : (data[j].chargeLevel == 2 ?'乙':'丙'))+'</td>' +
            '</tr>';
        sumFee += data[j].redSumFee;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"></td>' +
        '<td colspan="15" style="border-right:none" class="text-left">' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right switch-off">合计现金：' + (sumFee).toFixed(2) + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">合计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//检验检查表格
function createJJ(data, words) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>' + words + '</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-ed=' + data[0].examineId + '>' +
        '<thead><tr>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">项目名称</td>' +
        '<td colspan="2">送检科室</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2">' + data[j].billType + '</td>' +
            '<td colspan="5">' + data[j].itemName + '</td>' +
            '<td colspan="2">' + data[j].depNames + '</td>' +
            '<td colspan="2">' + data[j].exdPrice + '</td>' +
            '<td colspan="2">' + data[j].exdQuantity + '</td>' +
            '<td colspan="2">' + data[j].itemUnit + '</td>' +
            '<td colspan="2">' + data[j].exdSumPrice + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">' + (data[j].catName||'') + '</td>' +
            '</tr>';
        sumFee += data[j].exdSumPrice;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"></td>' +
        '<td colspan="11" style="border-right:none" class="text-left">' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right switch-off">合计现金：' + sumFee + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">合计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//收费项表格
function createFee(data) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>收费项目开单</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-ed=' + data[0].examineId + '>' +
        '<thead><tr>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">项目名称</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2">' + data[j].billType + '</td>' +
            '<td colspan="5">' + data[j].itemName + '</td>' +
            '<td colspan="2">' + data[j].exdPrice + '</td>' +
            '<td colspan="2">' + data[j].exdQuantity + '</td>' +
            '<td colspan="2">' + data[j].itemUnit + '</td>' +
            '<td colspan="2">' + data[j].exdSumPrice + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '</tr>';
        sumFee += data[j].exdSumPrice;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"></td>' +
        '<td colspan="8" style="border-right:none" class="text-left">' +
        '</td>' +
        '<td colspan="11">' +
        '<span class="bold pull-right switch-off">合计现金：' + (sumFee).toFixed(2) + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">合计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//详情收起展开
function openTable(el) {
    var $div = $(el).parent();
    arrowRotate($div);
    if ($div.has('table').length) {
        $div.find('table').fadeToggle();
    }
}
//处方计费切换
function toggleFee(el) {
    var $table = $(el).parent('h4').siblings('table');
    var isChecked = $(el).prop('checked');
    if (isChecked) {
        $table.find('.switch-on').show();
        $table.find('.switch-off').hide();
    } else {
        $table.find('.switch-on').hide();
        $table.find('.switch-off').show();
    }
}
//箭头转换
function arrowRotate($div) {
    var $i = $div.find('i');
    if ($i.hasClass('arrow-rotate')) {
        $i.removeClass('arrow-rotate');
        $i.addClass('arrow-rotateRecover');
    } else {
        $i.removeClass('arrow-rotateRecover');
        $i.addClass('arrow-rotate');
    }

}
//退费
$('#returnFee').click(function () {
    $('#modal').attr("method", "returnMoney");
    $('#modal').load("returnMoney.html");
    $('#modal').on('hidden.bs.modal	', function () {
    })
    $('#modal').modal({
        keyboard: true
    });
})
// //补打
// $('#reprint').click(function () {
//     ajaxNormalPost('/chg/charges_info/invoiceInformation', {chargesId: userId}, function (res) {
//         if(res){
//             var data = {};
//             data.patName = res.data.patName;//姓名
//             data.billDate = res.data.billDate;//日期
//             data.sum = res.data.subMoney;//合计
//             data.sffName = res.data.sffName;//收款人
//             data.patCardNum = res.data.patCardNum;//门诊号
//             data.medicareCard = res.data.patientsWrapper.medicareCard==null?'':res.data.patientsWrapper.medicareCard;//医保卡号
//             //医保信息
//             data.settleMentInformation = res.data.settleMentInformation;
//
//             data.ticketFee0 = res.data.ticketInfoWrapperList[0].ticketFee==null?'':res.data.ticketInfoWrapperList[0].ticketFee;
//             data.ticketFee1 = res.data.ticketInfoWrapperList[1].ticketFee==null?'':res.data.ticketInfoWrapperList[1].ticketFee;
//             data.ticketFee2 = res.data.ticketInfoWrapperList[2].ticketFee==null?'':res.data.ticketInfoWrapperList[2].ticketFee;
//             data.ticketFee3 = res.data.ticketInfoWrapperList[3].ticketFee==null?'':res.data.ticketInfoWrapperList[3].ticketFee;
//             data.ticketFee4 = res.data.ticketInfoWrapperList[4].ticketFee==null?'':res.data.ticketInfoWrapperList[4].ticketFee;
//             data.ticketFee5 = res.data.ticketInfoWrapperList[5].ticketFee==null?'':res.data.ticketInfoWrapperList[5].ticketFee;
//             data.ticketFee6 = res.data.ticketInfoWrapperList[6].ticketFee==null?'':res.data.ticketInfoWrapperList[6].ticketFee;
//             data.ticketFee7 = res.data.ticketInfoWrapperList[7].ticketFee==null?'':res.data.ticketInfoWrapperList[7].ticketFee;
//             data.ticketFee8 = res.data.ticketInfoWrapperList[8].ticketFee==null?'':res.data.ticketInfoWrapperList[8].ticketFee;
//             data.ticketFee9 = res.data.ticketInfoWrapperList[9].ticketFee==null?'':res.data.ticketInfoWrapperList[9].ticketFee;
//             data.ticketFee10 = res.data.ticketInfoWrapperList[10].ticketFee==null?'':res.data.ticketInfoWrapperList[10].ticketFee;
//             data.ticketFee11 = res.data.ticketInfoWrapperList[11].ticketFee==null?'':res.data.ticketInfoWrapperList[11].ticketFee;
//             data.ticketFee12 = res.data.ticketInfoWrapperList[12].ticketFee==null?'':res.data.ticketInfoWrapperList[12].ticketFee;
//             data.ticketFee13 = res.data.ticketInfoWrapperList[13].ticketFee==null?'':res.data.ticketInfoWrapperList[13].ticketFee;
//             data.ticketFee14 = res.data.ticketInfoWrapperList[14].ticketFee==null?'':res.data.ticketInfoWrapperList[14].ticketFee;
//             data.ticketFee15 = res.data.ticketInfoWrapperList[15].ticketFee==null?'':res.data.ticketInfoWrapperList[15].ticketFee;
//
//
//
//             var table = '<table style="font-size:10px;padding: 0;margin: 0">'
//             var item = '';
//             for (var i = 0; i < res.data.chargesProjectList.length; i++){
//                     item = res.data.chargesProjectList[i];
//                     table+='<tr style="height: 10px;line-height: 10px">' +
//                         '<td style="width: 140px">(' + (i+1)+')  '+item.drgName+' </td>' +
//                         '<td style="width: 50px">' + item.typeName + '</td>' +
//                         '<td style="width: 30px">' + item.quantity+item.drgPackingUnit + '</td>' +
//                         '<td style="width: 60px">' + item.sumPrice + '</td>' +
//                         '<td style="width: 60px;text-align:center;">' + (item.feeNum||'100%') + '</td>' +
//                         '</tr>'
//                     if(i>14){
//                         table += '<tr style="height: 10px;line-height: 10px"><td colspan="5">收费发票纸张有限，其余明细未打印</td></tr>'
//                     }
//             }
//             data.table = table;
//             var printerType;
//             ajaxNormalPost('/pub/dictionary/select_by_dic_code', {search_dicCode: 'DYJLX',search_chinaSpell: 'FYQD'}, function (res) {
//                 if (res.data.length >0) {
//                     printerType = res.data[0].id;
//                 }else{
//                     layer.msg('无此类型打印机，请前去维护')
//                 }
//             });
//             log4j.info(printerType)
//             var index;
//             ajaxNormalPost('/pub/PrinterManagement/select_list', {"search_hospitalId": hospitalId,"search_macAddress":macAddress,"search_printerType":printerType}, function (res) {
//                 if(res.data.length >0){
//                     index=res.data[0].printerIndex;
//                 }else{
//                     layer.msg('请维护打印机')
//                 }
//             });
//             invoiceInformationPrint(data,index);
//         }
//     })
// });

//listPrint 明细清单列表打印
$('#listPrint').click(function () {
    ajaxNormalPost('/chg/charges_info/invoiceInformation', {chargesId: userId}, function (res) {
        if(res){
            var data = {};
            data.invoiceInfoWrapper = res.data.invoiceInfoWrapper
            data.patName = res.data.patName;//姓名
            data.billDate = res.data.billDate;//日期
            data.billFavorFee = res.data.billFavorFee || 0;//优惠金额
            data.billTotalFee = res.data.billTotalFee;//总金额
            data.sum = res.data.subMoney;//合计
            data.loginNum = res.data.loginNum;//收款人
            data.patCardNum = res.data.patCardNum;//门诊号
            data.medicareCard = res.data.patientsWrapper.medicareCard || ''    //医保卡号
            data.settleMentInformation = res.data.settleMentInformation || ''  //医保信息
            data.table = []
            let arrTicket = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
            arrTicket.forEach(item => {
                data['ticketFee' + item] = res.data.ticketInfoWrapperList[item].ticketFee || ''
            })
            let index = 0
            let pageTable = group(res.data.chargesProjectList, 27)
            pageTable.forEach(pageItem => {
                var table = "<style> table {width: 100%} table,td {text-align: center;border: 0px solid black;border-style: solid;border-collapse:collapse;font-size: 14px;}</style><table border='1'>"
                table += '<tr><td>项目/规格</td><td>类别</td><td>数量</td><td>金额</td><td>自理自费(%)</td></tr>'
                for (var i = 0; i < pageItem.length; i++){
                    index += 1
                    let item = pageItem[i]
                    table+='<tr>' +
                        '<td style="text-align: left;">(' + index +')  '+item.drgName+' </td>' +
                        '<td>' + item.medicalGrade + '</td>' +
                        '<td>' + item.quantity + '</td>' +
                        '<td>' + item.sumPrice + '</td>' +
                        '<td>' + (Math.round(item.redSelfScale * 100) + '%') + '</td>' +
                        '</tr>'
                }
                table += '</table>'
                data.table.push(table)
            })
            inListPrint(data,recipeIndex,res);
        }
    })
});

// 将一个数组分成多个数组
function group(arr, len) {
    let arrLength = Math.ceil(arr.length / len)
    let newArr = []
    for (let i = 0; i < arrLength; i++) {
        newArr.push(arr.splice(0, len))
    }
    return newArr
}



